package com.qf.leadnewsarticle.service;

import com.alibaba.fastjson.JSON;
import com.qf.leadnewsarticle.model.vos.ArticleVo;
import com.qf.leadnewsmodel.consts.BehaviorConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class RedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void bitmap(String key, Long offset, Integer ops) {
        redisTemplate.opsForValue().setBit(key,offset,ops==0);
    }

    public boolean isTrue(String key,Long offset){
        return redisTemplate.opsForValue().getBit(key,offset);
    }

    /**
     * 根据key，获取这个key对应的bitmap统计数量
     * @param readKey
     * @return
     */
    public long getBitmapCount(String readKey) {
        try(RedisConnection conn = redisTemplate.getConnectionFactory().getConnection();){
            return conn.bitCount(readKey.getBytes(StandardCharsets.UTF_8));
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    /**
     *  缓存对应频道的数据
     *      channel如果为 all，表示推荐频道
     *      channel如果是其他值，表示其他频道 java\mysql
     * @param channel
     * @param articleVos
     */
    public void cache(String channel, List<ArticleVo> articleVos) {
        String jsonStr = JSON.toJSONString(articleVos);

        redisTemplate.opsForValue().set(BehaviorConst.ARTICLE_CACHE_PREFIX+channel,jsonStr);
    }

    /**
     * 获取指定频道的缓存数据
     * @param channel
     * @return
     */
    public String getCache(String channel) {
        return redisTemplate.opsForValue().get(BehaviorConst.ARTICLE_CACHE_PREFIX+channel);
    }
}
